package com.moyun.modelclass.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.ClickUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.SpanUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.moyun.modelclass.event.LoginStateEvent;
import com.moyun.modelclass.R;
import com.moyun.modelclass.base.BaseActivity;
import com.moyun.modelclass.http.api.AppAuthLoginApi;
import com.moyun.modelclass.http.api.AppCodeLoginApi;
import com.moyun.modelclass.http.model.HttpData;

import org.greenrobot.eventbus.EventBus;

/**
 * 作者：Meteor
 * 日期：2022/1/15 17:25
 * tip：验证码登录
 */
public class LoginVerificationCodeActivity extends BaseActivity {
    private ImageView loginVerificationCodeBack;
    private EditText loginVerificationCodeInputAccount;
    private EditText loginVerificationCodeInputVerificationCode;
    private TextView loginVerificationCodeGetVerificationCode;
    private TextView loginVerificationCodeTip;
    private TextView loginVerificationCodeButtonLogin;
    private ImageView loginVerificationCodeSelectAgree;
    private TextView loginVerificationCodeAgreement;

    private int times = 60;
    private int TIME_MESSAGE = 1;
    private boolean canSMS = true;
    private String mGuid = "";//guid，后续验证短信对应关系

    public static void start(Context context) {
        Intent starter = new Intent(context, LoginVerificationCodeActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_login_verification_code;
    }

    @Override
    protected void assignViews() {
        loginVerificationCodeBack = (ImageView) findViewById(R.id.login_verification_code_back);
        loginVerificationCodeInputAccount = (EditText) findViewById(R.id.login_verification_code_input_account);
        loginVerificationCodeInputVerificationCode = (EditText) findViewById(R.id.login_verification_code_input_verification_code);
        loginVerificationCodeGetVerificationCode = (TextView) findViewById(R.id.login_verification_code_get_verification_code);
        loginVerificationCodeTip = (TextView) findViewById(R.id.login_verification_code_tip);
        loginVerificationCodeButtonLogin = (TextView) findViewById(R.id.login_verification_code_button_login);
        loginVerificationCodeSelectAgree = (ImageView) findViewById(R.id.login_verification_select_agree);
        loginVerificationCodeAgreement = (TextView) findViewById(R.id.login_verification_code_agreement);

        loginVerificationCodeSelectAgree.setSelected(false);

        loginVerificationCodeAgreement.setMovementMethod(LinkMovementMethod.getInstance());
        SpanUtils.with(loginVerificationCodeAgreement)
                .append("我已阅读并同意")
                .append("《服务使用协议》")
                .setSpans(new ClickableSpan() {
                    @Override
                    public void onClick(@NonNull View widget) {
                        WebRichActivity.start(mActivity, "ServiceUsageAgreement");
                    }

                    @Override
                    public void updateDrawState(TextPaint ds) {
//                        super.updateDrawState(ds);
                        ds.setColor(Color.parseColor("#ff0ED3EA")); // 设置你想要的颜色
                        ds.setUnderlineText(false); // 如果需要的话，取消下划线
                    }
                })
                .append("和")
                .append("《隐私政策》")
                .setSpans(new ClickableSpan() {
                    @Override
                    public void onClick(@NonNull View widget) {
                        WebRichActivity.start(mActivity, "PrivacyAgreement");
                    }

                    @Override
                    public void updateDrawState(TextPaint ds) {
//                        super.updateDrawState(ds);
                        ds.setColor(Color.parseColor("#ff0ED3EA")); // 设置你想要的颜色
                        ds.setUnderlineText(false); // 如果需要的话，取消下划线
                    }
                })
                .create();
    }

    @Override
    protected void registerListeners() {
        ClickUtils.applySingleDebouncing(loginVerificationCodeBack, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        //获取验证码
        ClickUtils.applySingleDebouncing(loginVerificationCodeGetVerificationCode, 2000,new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!canSMS) {
                    return;
                }
                String account = loginVerificationCodeInputAccount.getText().toString().trim();
                if (RegexUtils.isMobileSimple(account)) {
                    EasyHttp.post(LoginVerificationCodeActivity.this)
                            .api(new AppCodeLoginApi().setMobile(account).setSmsType(1))
                            .request(new HttpCallback<HttpData<AppCodeLoginApi.Bean>>(LoginVerificationCodeActivity.this) {
                                @SuppressLint("SetTextI18n")
                                @Override
                                public void onSucceed(HttpData<AppCodeLoginApi.Bean> result) {
                                    if (result.getCode() == 1) {
                                        mGuid = result.getData().getGuid();
                                        times = 60;
                                        mHandler.sendEmptyMessage(TIME_MESSAGE);
                                        loginVerificationCodeInputVerificationCode.requestFocus();
                                    } else {
                                        ToastUtils.showShort(result.getMessage());
                                    }
                                }
                            });
                } else {
                    ToastUtils.showShort("请输入正确的手机号");
                }
            }
        });

        ClickUtils.applySingleDebouncing(loginVerificationCodeSelectAgree, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean selected = loginVerificationCodeSelectAgree.isSelected();
                loginVerificationCodeSelectAgree.setSelected(!selected);
            }
        });

        //登录
        ClickUtils.applySingleDebouncing(loginVerificationCodeButtonLogin, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                KeyboardUtils.hideSoftInput(LoginVerificationCodeActivity.this);
                String phone = loginVerificationCodeInputAccount.getText().toString().trim();
                String code = loginVerificationCodeInputVerificationCode.getText().toString().trim();
                if (TextUtils.isEmpty(phone)) {
                    ToastUtils.showShort("请输入您的手机号");
                    return;
                }

                if (!RegexUtils.isMobileSimple(phone)) {
                    ToastUtils.showShort("请输入正确的手机号");
                    return;
                }

                if (mGuid.equals("")) {
                    ToastUtils.showShort("请先获取验证码");
                    return;
                }

                if (TextUtils.isEmpty(code)) {
                    ToastUtils.showShort("请输入验证码");
                    return;
                }

                if (!loginVerificationCodeSelectAgree.isSelected()) {
                    ToastUtils.showShort("请先同意协议");
                    return;
                }

                try {
                    EasyHttp.post(LoginVerificationCodeActivity.this)
                            .api(new AppAuthLoginApi().setMobile(phone).setGuid(mGuid).setVerifyCode(code))
                            .request(new HttpCallback<HttpData<AppAuthLoginApi.Bean>>(LoginVerificationCodeActivity.this) {
                                @SuppressLint("SetTextI18n")
                                @Override
                                public void onSucceed(HttpData<AppAuthLoginApi.Bean> result) {
                                    if (result.getCode() == 1) {
                                        EventBus.getDefault().post(new LoginStateEvent(1));
                                        loginVerificationCodeTip.setVisibility(View.INVISIBLE);
                                        kv.encode("userTokenInfo", result.getData().getToken());
                                        kv.encode("userIdInfo", result.getData().getUserId());
                                        ToastUtils.showShort("登录成功");
                                        finish();
                                    } else {
                                        loginVerificationCodeTip.setText("错误提示:" + result.getMessage());
                                        loginVerificationCodeTip.setVisibility(View.VISIBLE);
                                    }
                                }
                            });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void getExtras(Bundle bundle) {

    }

    @Override
    protected boolean isRegisterEventBus() {
        return false;
    }

    @Override
    protected void doAction() {

    }

    @SuppressLint({"HandlerLeak", "DefaultLocale"})
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        public void handleMessage(Message msg) {
            times--;
            if (times > 0) {
                canSMS = false;
                sendEmptyMessageDelayed(TIME_MESSAGE, 1000);
                loginVerificationCodeGetVerificationCode.setText(String.format("%ds重新获取", times));
            } else {
                canSMS = true;
                removeCallbacksAndMessages(null);
                loginVerificationCodeGetVerificationCode.setText("重新获取");
            }
        }
    };
}
